#!/bin/sh /etc/rc.common

USE_PROCD=1
START=95
STOP=01

log() {
    local msg="$1"
    logger -t naywatch "$msg"
}

wait_for_network()
{
    ubus -t 15 wait_for network.interface.$1 2>/dev/null
}

boot()
{
    local _interfaces
    config_load naywatch
    config_get _interfaces general interface

    for interface in $_interfaces; do
        wait_for_network interface
    done

    rc_procd start_service
}

start_service() {
    procd_open_instance

    config_load naywatch
    local _check_interval
    local _watchdog_timeout
    local _use_watchdog
    local _save_logs
    local _interfaces

    config_get _check_interval general "check_interval"
    config_get _watchdog_timeout general "watchdog_timeout"
    config_get _use_watchdog general "use_watchdog"
    config_get _save_logs general "save_logs"
    config_get _interfaces general "interface"

    procd_set_param command /usr/bin/naywatch "$_check_interval" "$_watchdog_timeout" "$_use_watchdog" "$_save_logs" "$_interfaces"

    procd_set_param respawn 3600 15 0

    procd_set_param stdout 1
    procd_set_param stderr 1

    procd_close_instance
}

stop_service() {
    exec 3>&- # close file again
    sync && wait
}

service_stopped() {
    log "Naywatch Stopped!"
    log "Handover Watchdog to procd again:"
    ubus call system watchdog '{"magicclose":true,"stop":false}' > /dev/null
}
